package com.cloudbroker.bcs.csvc.base.api.export.rest.base;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;

import com.cloudbroker.bcs.common.jres.util.JresUtil;

public class HSBCCSRESTBase {
    
    @Autowired
    protected HttpServletRequest request;
    
    public String getUserToken() {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(authorization)) {
            return authorization.substring("Bearer ".length());
        } else {
            return null;
        }
    }
    
    public Map<String, Object> toJresMap(Map<String, Object> rawParam) {
        Map<String, Object> param = JresUtil.bodyProtocolToJresMap(rawParam);
        String userToken = getUserToken();
        if (StringUtils.isNotBlank(userToken)) {
            param.put("user_token", userToken);
			param.put("user_key", userToken);
        }
        return param;
    }
    
    public Map<String, Object> toJresMap(MultiValueMap<String, Object> rawParam) {
        Map<String, Object> bodyParam = rawParam.toSingleValueMap();
        Map<String, Object> param = JresUtil.bodyProtocolToJresMap(bodyParam);
        String userToken = getUserToken();
        if (StringUtils.isNotBlank(userToken)) {
            param.put("user_token", userToken);
			param.put("user_key", userToken);
        }
        return param;
    }
    
    public Map<String, Object> readJresMap(Map<String, Object> jresMap) {
        return JresUtil.bodyProtocolToRawMap(jresMap);
    }
    
}
